package com.wanpinghui.wphlibrary.model.addrbook;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.wanpinghui.wphlibrary.common.IWPHApi;
import com.wanpinghui.wphlibrary.model.addrbook.bean.AddrbookBean;
import com.wanpinghui.wphlibrary.model.addrbook.bean.MobileListBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.order.bean.PageDataBean;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.Network;
import retrofit.callback.YRequestCallback;
import retrofit.callback.YunShlAction;
import retrofit.callback.YunShlResult;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 功能描述
 * author:caitiangui
 * time:2018/1/3
 */

public class AddrbookServiceImp implements AddrbookService {

    @Override
    public void addressBookList(int type, int page, final YRequestCallback<PageDataBean<AddrbookBean>> callback) {
        Network.getYSApi(IWPHApi.class).addressBookList(type,page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<PageDataBean<AddrbookBean>>>() {
                    @Override
                    public void call(YunShlResult<PageDataBean<AddrbookBean>> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void mobil_list(int page,int per_page,int page_type,final YRequestCallback<MobileListBean> callback) {
//        Map<String,Object> params = new HashMap<>();
//        params.put("page", page);
//        params.put("per_page",per_page);

        Network.getApi(IWPHApi.class).mobilList(page,per_page,page_type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<MobileListBean>>() {
                    @Override
                    public void call(YunShlResult<MobileListBean> mobileListBeanYunShlResult) {
                        if (callback != null){
                            if (mobileListBeanYunShlResult.isSuccess()){
                                callback.onSuccess(mobileListBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,mobileListBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void addFriends(String followed_id, final YRequestCallback<Object> callback) {
//        Map<String,Object> params = new HashMap<>();
//        params.put("followed_id", followed_id);
        Network.getApi(IWPHApi.class).addFriends(followed_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> objectYunShlResult) {
                        if (callback != null){
                            if (objectYunShlResult.isSuccess()){
                                callback.onSuccess(objectYunShlResult.body);
                            }else {
                                callback.onFailed(0,objectYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));

    }

    @Override
    public void getUserInfo(long user_id, final YRequestCallback<UserBean> callback) {
        Network.getApi(IWPHApi.class).getUserInfo(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<UserBean>>() {
                    @Override
                    public void call(YunShlResult<UserBean> userBeanYunShlResult) {
                        if (callback != null){
                            if (userBeanYunShlResult.isSuccess()){
                                callback.onSuccess(userBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,userBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void addfriendsLogs(final YRequestCallback<MobileListBean> callback) {
        Network.getApi(IWPHApi.class).addFriendsLogs()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<MobileListBean>>() {
                    @Override
                    public void call(YunShlResult<MobileListBean> mobileListBeanYunShlResult) {
                        if (callback != null){
                            if (mobileListBeanYunShlResult.isSuccess()){
                                callback.onSuccess(mobileListBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,mobileListBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void agreeAddFriendsLogs(long invite_id,final YRequestCallback<MobileListBean> callback) {
        Map<String,Object> params = new HashMap<>();
        params.put("invite_id", invite_id);
        Network.getApi(IWPHApi.class).agreeAddFriendsLogs(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<MobileListBean>>() {
                    @Override
                    public void call(YunShlResult<MobileListBean> mobileListBeanYunShlResult) {
                        if (callback != null){
                            if (mobileListBeanYunShlResult.isSuccess()){
                                callback.onSuccess(mobileListBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,mobileListBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void updateMobilList(List<String> list, final YRequestCallback<Object> callback) {
        Map<String,List<String>> params = new HashMap<>();
        params.put("mobiles", list);
        LogUtils.d("mobiles",list.toString());
        Network.getApi(IWPHApi.class).updateMobilList(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<MobileListBean>>() {
                    @Override
                    public void call(YunShlResult<MobileListBean> mobileListBeanYunShlResult) {
                        if (callback != null){
                            if (mobileListBeanYunShlResult.isSuccess()){
                                callback.onSuccess(mobileListBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,mobileListBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    public void readContact(final Context context, final YRequestCallback<ArrayList<HashMap<String, String>>> callback) {
        // 首先,从raw_contacts中读取联系人的id("contact_id")
        // 其次, 根据contact_id从data表中查询出相应的电话号码和联系人名称
        // 然后,根据mimetype来区分哪个是联系人,哪个是电话号码
        // 从raw_contacts中读取所有联系人的id("contact_id")
        Observable.create(new Observable.OnSubscribe<ArrayList<HashMap<String, String>>>() {
            @Override
            public void call(Subscriber<? super ArrayList<HashMap<String, String>>> subscriber) {
                Uri rawContactsUri = Uri.parse("content://com.android.contacts/raw_contacts");
                Uri dataUri = Uri.parse("content://com.android.contacts/data");
                ArrayList<HashMap<String, String>> list = new ArrayList<>();
                Cursor rawContactsCursor = context.getContentResolver().query(rawContactsUri,
                        new String[] { "contact_id" }, null, null, null);
                if (rawContactsCursor != null) {
                    while (rawContactsCursor.moveToNext()) {
                        String contactId = rawContactsCursor.getString(0);
                        // System.out.println("得到的contact_id="+contactId);

                        // 根据contact_id从data表中查询出相应的电话号码和联系人名称, 实际上查询的是视图view_data
                        Cursor dataCursor = context.getContentResolver().query(dataUri,
                                new String[] { "data1", "mimetype" }, "contact_id=?",
                                new String[] { contactId }, null);

                        if (dataCursor != null) {
                            HashMap<String, String> map = new HashMap<>();
                            while (dataCursor.moveToNext()) {
                                String data1 = dataCursor.getString(0);
                                String mimetype = dataCursor.getString(1);

                                // System.out.println(contactId + ";" + data1 + ";"
                                // + mimetype);

                                if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {//手机号码
                                    if (data1.contains(" ")){
                                        data1 = data1.replace(" ","");
                                    }
                                    if (data1.length()==11 ) {
                                        map.put("phone", data1);
                                    }
                                } else if ("vnd.android.cursor.item/name".equals(mimetype)) {//联系人名字
                                    map.put("name", data1);
                                }
                            }
                            if (TextUtil.isNotEmpty(map.get("phone")) && TextUtil.isNotEmpty(map.get("name"))) {
                                list.add(map);
                            }
                            dataCursor.close();
                        }
                    }
                    subscriber.onNext(list);
                    rawContactsCursor.close();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<ArrayList<HashMap<String, String>>>() {
            @Override
            public void call(ArrayList<HashMap<String, String>> hashMaps) {
                if (callback != null) {
                    callback.onSuccess(hashMaps);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
        //return list;
    }

    @Override
    public void friends(final YRequestCallback<MobileListBean> callback) {
        Network.getApi(IWPHApi.class).friends()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<MobileListBean>>() {
                    @Override
                    public void call(YunShlResult<MobileListBean> mobileListBeanYunShlResult) {
                        if (callback != null){
                            if (mobileListBeanYunShlResult.isSuccess()){
                                callback.onSuccess(mobileListBeanYunShlResult.body);
                            }else {
                                callback.onFailed(0,mobileListBeanYunShlResult.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void unReadCount(final YRequestCallback<RecentMsgBean> callback) {
        Network.getApi(IWPHApi.class).unReadCount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<RecentMsgBean>>() {
                    @Override
                    public void call(YunShlResult<RecentMsgBean> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void inviteFriends(String mobiles,String nickname, final YRequestCallback<Object> callback) {
        Map<String,String> params = new HashMap<>();
        params.put("mobile", mobiles);
        params.put("nickname",nickname);

        Network.getApi(IWPHApi.class).invitefriends(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }

    @Override
    public void call(String user_id, final YRequestCallback<Object> callback) {
        Network.getApi(IWPHApi.class).call(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (callback != null){
                            if (result.isSuccess()){
                                callback.onSuccess(result.body);
                            }else {
                                callback.onFailed(0,result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback));
    }
}
